package com.ssm.controller;

import com.ssm.common.Result;
import com.ssm.common.ResultGenerator;
import com.ssm.entity.PageBean;
import com.ssm.entity.User;
import com.ssm.service.UserService;
import com.ssm.utils.MD5Util;
import com.ssm.utils.ResponseUtil;
import com.ssm.utils.StringUtil;
import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LinYaTing on 2018/12/7 16:46
 */
@Controller
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    private UserService userService;

    private static final Logger log = Logger.getLogger(UserController.class);

    /**
     * 登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(User user) {
        String password = MD5Util.MD5Encode(user.getPassword(), "UTF-8");
        user.setPassword(password);
        User userResult = userService.login(user);
        log.info("request: user/login, user:" + user.toString());
        if (userResult == null) {
            return ResultGenerator.getFailResult("请认真核对账号密码！");
        }else {
             userResult.setPassword("PASSWORD");
            Map data = new HashMap();
            data.put("currentUser", userResult);
            return ResultGenerator.getSuccessResult(data);

        }
    }

    /**
     * @param page
     * @param rows
     * @param s_user
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/datagrid", method = RequestMethod.POST)
    public String list(@RequestParam(value = "page",required = false) String page, @RequestParam(value = "rows", required = false) String rows, User s_user, HttpServletResponse response) throws Exception {
        PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
        Map<String, Object> map = new HashMap<>();
        map.put("userName", StringUtil.formatLike(s_user.getUserName()));
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        List<User> userList = userService.findUser(map);
        Long total = userService.getTotalUser(map);
        JSONObject result = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(userList);
        result.put("rows", jsonArray);
        result.put("total", total);
        log.info("request: user/list, map:" + map.toString());
        ResponseUtil.write(response, result);
        return null;
    }
}
